package com.syp.envops.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.syp.auth.domain.ProcessResult;
import com.syp.auth.export.annotation.SecurityNone;
import com.syp.auth.export.common.TokenCooikeMaster;
import com.syp.auth.export.resource.AuthorizeResourceI;
import com.syp.envops.util.StringEscapeEditor;

@Controller
@RequestMapping({ "/" })
public class BaseController {
	
	private static final Logger log = LoggerFactory.getLogger(BaseController.class);
	
	@Autowired
	private AuthorizeResourceI authorizeResource;
		
	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
		binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
	}
	
	@RequestMapping({ "/index", "/" })
	public String index(HttpServletRequest request) {
		return "index";
	}
	
	@SecurityNone
	@RequestMapping("/signout")
	@ResponseBody
	public Object signout(HttpServletRequest request, HttpServletResponse response) {
		try {
			Cookie oldtoken = TokenCooikeMaster.getInstunce().remove(request, response);
			if (oldtoken != null) {
				this.authorizeResource.signout(oldtoken.getValue());
			}
		} catch (Exception e) {
			log.error("退出登录异常。", e);
		}

		return new ProcessResult(true, "退出登录成功。");
	}
}